<template>
  <up-form-item prop="location" ref="itemInputPositionRef">
    <view class="posotionArea">
      <up-icon name="empty-address" color="#36A1EE" size="40rpx"></up-icon>
      <view class="addressView" @click="getPosition">
        {{ addressText }}
      </view>
    </view>
  </up-form-item>
</template>

<script setup>
import {
  ref,
  getCurrentInstance,
  toRef,
  inject,
  computed,
  watch,
  nextTick,
  onMounted,
} from "vue";
import { useStore } from "vuex";

const { proxy } = getCurrentInstance();

const store = useStore();

const addressText = ref("获取定位信息");
const addressInfo = ref({});

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {},
  },
});
const modelValue = toRef(props, "modelValue");
const emit = defineEmits(["update:modelValue"]);

const getPosition = async () => {
  addressText.value = "位置信息获取中";
  const res = await store
    .dispatch("position/getPosition", {
      reverseGeocoder: true,
      settingTitle: "请求授权当前位置",
      settingContent: "需要获取您的地理位置，提高您的帖子的曝光率！",
    })
    .catch(() => {
      addressText.value = "获取失败，请重新获取";
    });

  if (!res) return false;

  const address_component = res.reverseGeocoderResult.address_component;
  addressInfo.value.latitude = res.latitude;
  addressInfo.value.longitude = res.longitude;
  addressInfo.value.locationId = `${address_component.province},${address_component.city},${address_component.district}`;
  addressInfo.value.location = `${address_component.province},${address_component.city},${address_component.district}`;

  addressText.value = `${address_component.city}·${address_component.district}`;
  change();
};

onMounted(() => {
  getPosition();
});

const change = () => {
  emit("update:modelValue", {
    ...props.modelValue,
    ...addressInfo.value,
  });
};
</script>

<style lang="scss">
.posotionArea {
  padding: 0 24rpx;
  border-radius: 10rpx;
  overflow: hidden;
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #333333;
}
</style>
